var currEnterprise = {};
var userId = $("input[name=userId]").val();
if (userId && userId !== '') {
    $.get("enterprise/getByUserId/" + userId, function (enterprise) {
        if (enterprise) {
            $("#loginName").val(enterprise.user.loginName);
            $("#name").val(enterprise.name);
            $("#shortName").val(enterprise.shortName);
            $("#orgCode").val(enterprise.orgCode);
            $("#bizLicense").val(enterprise.bizLicense);
            $("#taxRegNo").val(enterprise.taxRegNo);
            $("#bankLicense").val(enterprise.bankLicense);
            currEnterprise = enterprise;
        }
    });
}

/**
 * 初始化表单验证
 * 
 * @param {type} param
 */
$("#enterpriseForm").validate({
    //错误类名和元素标签类型
    errorClass: "gg-error",
    validClass: "gg-success",
    errorElement: "label",
    //验证规则正则表达式
    rules: {
        loginName: {
            required: true,
            regx: /^[a-zA-Z0-9_\u4e00-\u9fb9]{2,30}$/,
            remote: "user/isLoginNameAvailable?&id=" + userId
        },
        name: {
            required: true,
            remote: "enterprise/isNameAvailable?&id=" + userId
        },
        orgCode: {
            required: true
        },
        bizLicense: {
            required: true
        },
        taxRegNo: {
            required: true
        }
    },
    //验证结果文字提示
    messages: {
        loginName: {
            required: '必填',
            regx: '格式不正确',
            remote: '已存在'
        },
        name: {
            required: '必填',
            remote: '已存在'
        },
        orgCode: {
            required: '必填'
        },
        bizLicense: {
            required: '必填'
        },
        taxRegNo: {
            required: '必填'
        }
    },
    //验证结果处理
    highlight: function (element, errorClass, validClass) {
        $(element).closest('.form-group').addClass(errorClass).removeClass(validClass);
    },
    unhighlight: function (element, errorClass, validClass) {
        $(element).closest('.form-group').removeClass(errorClass).addClass(validClass);
    },
    //错误信息位置
    errorPlacement: function (error, element) {
        error.insertAfter(element);
    }
});

/**
 * 提交表单
 * 
 * @param {type} param
 */
$("#saveEnterpriseBtn").click(function () {
    if ($("#enterpriseForm").valid()) {
        var data = $("#enterpriseForm").formToJson();
        $.post("enterprise/save", data, function (res) {
            alert(res.message);
            if (res.success) {
                location.href = "enterprise/list";
            }
        }).fail(function () {
            alert("网络通信错误");
        });
    }
});